package com.maolong.delayedprod.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


@Slf4j
@Configuration
@ConfigurationProperties("spring.rabbitmq")
@Data
@EnableRabbit
public class RabbitConfig {
    private String host;
    private int port;
    private String username;
    private String password;

    private static final String EXCHANGE_NAME="delayed_exchange";
    private static final String QUEUE_NAME="delayed_queue";
    private static final String EXCHANGE_SUCCESS="exchange_success";
    private static final String QUEUE_SUCCESS="queue_success";

    @Bean
    public CachingConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        return connectionFactory;
    }
    @Bean
    public RabbitTemplate rabbitTemplate(AckCallBack ackCallBack,ReturnCallBack returnCallBack){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        rabbitTemplate.setConfirmCallback(ackCallBack);
        rabbitTemplate.setReturnsCallback(returnCallBack);
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

    /**
     * 绑定延时队列和延时交换机
     * 当信息传递到这个延时队列中时，代表消息已经超时间了，此时来检查队列中的消息是否已经完成支付
     * @return
     */
    @Bean
    public Queue delayedQueue(){
        return new Queue(QUEUE_NAME);

    }
    @Bean
    public CustomExchange delayedExchange(){
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type","topic");
        return new CustomExchange(EXCHANGE_NAME,"x-delayed-message",true,false,arguments);
    }
    @Bean
    public Binding bindingDelayed(){
        return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with("fail.#").noargs();
    }



}
